package com.yq.tanhua.ui.contract

import android.content.ClipData.Item
import android.os.Bundle
import android.os.PersistableBundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.lifecycleScope
import com.yq.tanhua.net.TanHuaApiService
import com.yq.tanhua.net.vo.ContractVo
import com.yq.tanhua.net.vo.PageInfo
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow


class ContractActivity : AppCompatActivity() {

    private val datas = MutableStateFlow<PageInfo<ContractVo>?>(null)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val state = datas.collectAsState()
            Column(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = "联系人列表",
                    modifier = Modifier.align(Alignment.CenterHorizontally),
                    style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.Bold)
                )
                ContractList(pageInfo = state.value)
            }
        }
    }

    @Composable
    fun ContractList(pageInfo: PageInfo<ContractVo>?) {
        pageInfo?.let {
            LazyColumn(content = {
                it.items?.forEach { item ->
                    item { Text(text = item.nickname, modifier = Modifier.padding(10.dp)) }
                }
            }, modifier = Modifier.padding(10.dp))
        }
    }


    override fun onStart() {
        super.onStart()
        lifecycleScope.launchWhenStarted {
            loadContractData()
        }

    }


    private suspend fun loadContractData() {
        val contactsList = TanHuaApiService.contactsList().fullData()
        datas.value = contactsList
    }
}